package com.song.springclouddemoshardingjdbc.controller;

import com.song.springclouddemoshardingjdbc.entity.Order;
import com.song.springclouddemoshardingjdbc.entity.User;
import com.song.springclouddemoshardingjdbc.mapper.OrderMapper;
import com.song.springclouddemoshardingjdbc.mapper.UserMapper;
import com.song.springclouddemoshardingjdbc.service.UserOrderService;
import com.song.springclouddemoshardingjdbc.utils.DateUtils;

import io.shardingsphere.transaction.annotation.ShardingTransactionType;
import io.shardingsphere.transaction.api.TransactionType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Random;


/**
 * 单库：直接使用本地事务  @Transactional(rollbackFor = Exception.class)
 *
 * 跨库：分布式事务
 *      1.使用 两阶段XA事务 进行管理   @ShardingTransactionType(TransactionType.XA)
 *      2.使用  BASE柔性事务  进行管理
 *
 * 步骤：1. 导入依赖
 *         使用 XA 事务时，需要引入此模块
 *         <dependency>
 *             <groupId>org.apache.shardingsphere</groupId>
 *             <artifactId>shardingsphere-transaction-xa-core</artifactId>
 *             <version>5.0.0-alpha</version>
 *         </dependency>
 *      2. 使用注解
 *         @ShardingTransactionType(TransactionType.XA)   // 支持TransactionType.LOCAL, TransactionType.XA, TransactionType.BASE
 *         @Transactional(rollbackFor = Exception.class)
 *      3. 测试
 *         order存在 db1, user 存在 db2
 */

@RestController
@RequestMapping("/transaction")
public class TestTransactionController {
    @Autowired
    private UserOrderService userOrderService;


    // http://localhost:8888/transaction/save
    @GetMapping("/save")
    public String saveUsers(){

        // order存在 db1.order_202203, user 存在 ds2.user0
        Order order = new Order() {{
            setOrdernumber("DN202312250001");
            setUserid(227221L);
            setYearmonth("202203");
            setCreateTime(new Date());
        }};
        User user = new User() {{
            setNickname("Amami Yuki" + new Random().nextInt());
            setPassword("1234567");
            setSex(0);
            setAge(10);
            setBirthday(DateUtils.parseDate("2023-12-03"));
            setDbname("test");
        }};

        userOrderService.saveUserOrder(user,order);

        return "success";
    }








}
